import Request from "@/uni_modules/luch-request/index.js";

import {
	BASE_URL,
	MP_API_URL,
	USER_INFO,
	SYSTEM_CONFIG,
	TOKEN,
	REFRESH_TOKEN
} from "@/api/config.js";

const request = new Request()

request.setConfig((config) => {
	/* 设置全局配置 */
	config.header = {
		...config.header,
	}
	return config
})

// 请求拦截
request.interceptors.request.use((config) => { // 可使用async await 做异步操作
	config.baseURL = MP_API_URL
	config.header = {
		...config.header,
		token: uni.getStorageSync(TOKEN),
	}
	return config
}, err => {
	return Promise.reject(err)
})
// 防止重复刷新标志位
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []

// 响应拦截 
request.interceptors.response.use(async (response) => {  // 添加 async
    const accessToken = uni.getStorageSync(TOKEN)
    const refreshToken = uni.getStorageSync(REFRESH_TOKEN)
    if (response) {
        if (response.statusCode == 200 || response.data.code == 401) {
            if (response.data.code == 1) {
                return response.data
            } else if (response.data.code == 401 || response.code == 401) {
                const config = response.config
                uni.clearStorageSync();
                try {
                    const loginRes = await uni.login({
                        provider: 'weixin',
                        onlyAuthorize: true
                    });
                    const jsCode = loginRes.code;
                    const res = await uni.request({
                        url: MP_API_URL + `/index/wx/login/${jsCode}`,
                        method: 'POST'
                    });
                    
                    if (res.data.code === 200) {
                        // 登录成功，保存token和用户信息
                        uni.setStorageSync('token', res.data.data?.token);
                        uni.setStorageSync('userId', res.data.data?.userId);
                        uni.setStorageSync('bindCode', res.data.data?.bindCode);
                        uni.setStorageSync('bindType', res.data.data?.bindType);
                        this.getList();
                        // 重新发起原始请求
                        return uni.request(config);
                    } else {
                        // 处理其他情况
                        uni.showToast({
                            icon: 'error',
                            title: res.data.data.message || '登录失败',
                        });
                        return Promise.reject(res);
                    }
                } catch (error) {
                    return Promise.reject(error);
                }
            } else if (response.data.code == 0) {
                uni.showToast({
                    icon: 'error',
                    title: response.data.msg,
                });
                return Promise.reject(response);
            }
        }
    }
    return response;
}, err => {
    // 处理错误
    return Promise.reject(err);
});

export default request